package com.run.cat.common.base;


import com.run.cat.common.enums.CodeEnum;
import com.run.cat.common.exception.ApiException;
import com.run.cat.common.exception.SignException;
import com.run.cat.common.util.DateUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;


@Component
public class BaseApiController {

	@InitBinder
	public void initBuilder(WebDataBinder binder) {
		//防止xss攻击
		binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
			 @Override
	            public void setAsText(String text) {
	                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
	            }

	            @Override
	            public String getAsText() {
	                Object value = getValue();
	                return value != null ? value.toString() : "";
	            }
		});

		 // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });

        // Timestamp 类型转换
        binder.registerCustomEditor(Timestamp.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                Date date = DateUtils.parseDate(text);
                setValue(date == null ? null : new Timestamp(date.getTime()));
            }
        });

	}
	protected String checkException(Exception e){
		if(e instanceof SignException || e instanceof ApiException){
			return e.getMessage();
		}
		return CodeEnum.SERVICE_FAIL.getTop();
	}

	public boolean backBindingResult(BindingResult bindingResult, BaseResult baseResult) {
		if(bindingResult.hasErrors()) {
			List<ObjectError> allErrors = bindingResult.getAllErrors();
			for (ObjectError error : allErrors) {
				baseResult.setCode("-1");
				baseResult.setMessage(error.getDefaultMessage());
				return true;
			}
		}
		return false;
	}
}
